#include <iostream>
#include <unistd.h>
#include <ctime>

int gval = 100;

void fun()
{
    std::cout << "fun()" << std::endl;
}

// 新线程
void *threadStart(void *args)
{
    while (true)
    {
        sleep(1);

        // int x = rand() % 5;
        // std::cout << "x: " << x << std::endl;

        std::cout << "new thread running..." << ", pid: " << getpid()
                  << ", gval: " << gval << ", &gval: " << &gval << std::endl;
        
        fun();

        // if (x == 0)
        // {
        //     int *p = nullptr;
        //     *p = 100; // 野指针
        // }
    }
}

int main()
{
    pthread_t th1;
    pthread_create(&th1, nullptr, threadStart, (void *)"thread-new");

    pthread_t tid2;
    pthread_create(&tid2, nullptr, threadStart, (void *)"thread-new");

    pthread_t tid3;
    pthread_create(&tid3, nullptr, threadStart, (void *)"thread-new");

    // 主线程
    while (true)
    {
        std::cout << "main thread running..." << ", pid: " << getpid()
                  << ", gval: " << gval << ", &gval: " << &gval << std::endl;
        gval++; // 修改！
        sleep(1);
    }

    return 0;
}